import { useUserStore } from "@/store/user";
import type { BaseResponse } from "@/types";
import { Message } from "@arco-design/web-vue";
import axios, { type AxiosRequestConfig } from "axios";
import QueryString from "qs";
import router from "@/router/index";
let source = axios.CancelToken.source();
const request = axios.create({
  baseURL: "/api",
  responseType: "blob",
  // @ts-ignore
  paramsSerializer: {
    serialize: (param: any) => {
      return QueryString.stringify(param, { arrayFormat: "repeat" });
    },
  },
  validateStatus: (status) => status < 500,
  timeout: 60000,
});
const getAuth = () => {
  const token = useUserStore().userCredit.token;
  return token ? `${token}` : (undefined as unknown as string);
};

request.interceptors.request.use(
  (req) => {
    req.cancelToken = source.token;
    req.headers.Authorization = getAuth();
    return req;
  },
  (err) => {
    return Promise.reject(err);
  }
);
let logout = false;
request.interceptors.response.use(async (response) => {
  const p = () =>
    new Promise<void>((resolve) => {
      if (response.data.type?.includes("application/json")) {
        const r = new FileReader();
        r.onload = () => {
          try {
            response.data = JSON.parse(r.result as string);
          } catch {
            response.data = {
              code: 400,
              message: "服务器发生未知错误",
            };
            resolve();
          }
          resolve();
        };
        r.readAsText(response.data);
      } else {
        resolve();
      }
    });
  await p();
  //401
  if (response.status !== 401) {
    logout = false;
  }
  if (response.status === 401) {
    source.cancel("登录信息已过期");
    if (!logout) {
      if (useUserStore().userCredit.token) {
        Message.error("登录信息已过期");
      } else {
        Message.error("用户不存在");
      }
    }
    logout = true;
    source = axios.CancelToken.source();
    router.replace("/login");
  }
  return response.data;
});

export function post<T = undefined>(
  url: string,
  data?: Object,
  options?: AxiosRequestConfig & {
    userApi: "message" | "modal" | "silent";
    apiType?: "error" | "info";
  }
) {
  const { userApi, apiType, ...restOptions } = options || {};
  if (data instanceof FormData) {
    console.log(data);
    return request.postForm<any, BaseResponse<T>>(url, data, {
      ...restOptions,
    } as any);
  }
  return request.post<any, BaseResponse<T>>(url, data, {
    ...restOptions,
  } as any);
}
export function get<T = undefined>(
  url: string,
  query?: Object,
  options?: AxiosRequestConfig
) {
  const { timeout, ...restOptions } = options || {};
  return request.get<any, BaseResponse<T>>(url, {
    params: query,
    timeout: (timeout || 1) * 60000,
    ...restOptions,
  } as any);
}
export function put<T = undefined>(url: string, data?: Object) {
  if (data instanceof FormData)
    return request.putForm<any, BaseResponse<T>>(url, data);
  return request.put<any, BaseResponse<T>>(url, data);
}
export function del<T = undefined>(url: string, data?: Object) {
  return request.delete<any, BaseResponse<T>>(url, {
    data,
  });
}
